<template>
    <div>
        <nav-bar>
            <template v-slot:left></template>
            <template v-slot:default>购物车</template>
            <template v-slot:right></template>
        </nav-bar>
        <div class="cart-box">
          <div class="cart-body">
            <van-checkbox-group ref="checkboxGroup"  @change="groupChange"  v-model="checkedup">
                
                  <van-swipe-cell v-for="(item,index) in list" :key="index">
                    <div class="good-item">
                      <van-checkbox :name="item.id" /> 
                      <div class="good-img"><img :src="item.goods.cover_url" alt=""></div>
                      <div class="good-desc">
                        <div class="good-title">
                          <span>{{item.goods.title}}</span>
                          <span><small>库存：</small>{{item.goods.stock}}</span>
                        </div>
                        <div class="good-btn">
                          <div class="price"><small>￥</small>{{item.goods.price + '.00'}}</div>
                          <van-stepper  theme="round" button-size="22" 
                          :name="item.id"
                          :min="1" 
                          :max="item.goods.stock"
                          :model-value="item.num"
                          disable-input 
                          @change="onChange"
                          />
                        </div>
                      </div>
                    </div>
                    <template #right>
                      <van-button square text="删除" type="danger" class="delete-button" @click="deleteGoods(item.id)"/>
                    </template>
                    <van-divider />
                  </van-swipe-cell>

                  
            </van-checkbox-group>
          </div>

          <van-submit-bar :price="total * 100" button-text="提交订单" @submit="onSubmit">
            <van-checkbox v-model="checked" @click="allCheck">全选</van-checkbox>
          </van-submit-bar>
          <div class="empty" v-if="!list.length">
            <van-icon name="cart-o" dot   size="130" color="red"/>
            <div class="title" >购物车为空</div>
            <van-button round color="var(--color-tint)" type="primary" block @click="goTo">去购买</van-button>
          </div>
          
        </div>
    </div>
</template>

<script>
import NavBar from 'components/common/navbar/NavBar';
import {reactive,onMounted,toRefs,computed} from 'vue';
import {getCart,modifyCart,checkedCart,delCart} from 'network/cart';
import { Toast } from 'vant';
import {useRouter} from 'vue-router';
import {useStore} from 'vuex';

export default {
  name:"ShopCar",
    components:{
        NavBar
    },

  setup() {
    const store = useStore();
    const state = reactive({
      list:[],
      checkedup:[],  //name里的id数组
      checked:true,
    });
  
    // onMounted(()=>{
    //     if (location.href.indexOf("#reloaded") == -1) {
    //         location.href = location.href + "#reloaded";
    //         location.reload();
    //     }
    // });
   
    // 获取购物车列表数据
    const init = ()=>{
      Toast.loading({message:'加载中...',forbidClick:true});
      getCart('include=goods').then(res=>{
        console.log(res.data);
        state.list = res.data;
        state.checkedup = res.data.filter(n=>n.is_checked ==1).map(item => item.id);
        // console.log(state.checkedup);
      Toast.clear();
      })
    }
  

    onMounted(()=>{
      init();
    })
    
    //通过计算属性 计算总价
    const total = computed(()=>{
      let sum = 0;

      state.list.filter(item=>state.checkedup.includes(item.id)).forEach(item=>{
        sum += parseInt(item.num) * parseFloat(item.goods.price) ;   //   parseInt是整数 价格转成parseFloat浮点
      })

      return sum;
    })


    // 异步改变购物车数量
    const onChange = (value,detail)=>{
      Toast.loading({message:'修改中...',forbidClick:true});
      console.log(value);
      console.log(detail);

      modifyCart(detail.name,{num:value}).then(res=>{
        //将在onMounted中list中的num也要改
        state.list.forEach(item=>{
          if(item.id == detail.name){
            item.num = value;
          }
        })
        Toast.clear();
      })
    }

    //复选框改变处理 checkedup为默认的双向绑定
    const groupChange = (checkedup) =>{
      //判断全选的默认显示状态
      if(checkedup.length == state.list.length){
        state.checked = true;
      }else {
        state.checked = false;
      }
      console.log(checkedup);
      state.checkedup = checkedup;
      //cart_ids改变购物车数据表中的选中状态 
      checkedCart({cart_ids:checkedup}); 

    }
    //全选
    const allCheck = ()=>{
      if(state.checked) {
         state.checkedup = state.list.map(item=>item.id);
        state.checked = true;
      }else {
        state.checkedup =[];
        state.checked = false;
      }
    }
    //删除商品
    const deleteGoods =(id)=>{
      delCart(id).then(res=>{
        init();
        Toast.success('删除成功');
        //改变vuex状态数量
        store.dispatch('updateCart');
      })
    }

    //去购物
    const router = useRouter();
    const goTo = ()=>{
      router.push({path:'/cate'})
    }

    //提交订单
    const onSubmit =()=>{
      if(state.checkedup.length == 0){
        Toast.fail('请选择商品');
        return;
      }else{
        router.push({path:('/addorder')});
      }
    }


    return { 
      ...toRefs(state),
      onChange,
      goTo,
      groupChange,
      allCheck,
      deleteGoods,
      total,
      onSubmit
    };
  },
}
</script>

<style lang="scss">
.cart-box{
  .cart-body {
    margin: 60px 0 100px 0;
    padding-left: 10px;
  .good-item {
    display: flex;
    height: 90px;
  .good-img {
    img{
      width: 90px;
      height: auto;
    }
  }
  .good-desc {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    flex: 1;
    padding: 10px 20px 10px 0;
    .good-title {
    display: flex;
    justify-content: space-between;
    span{
      height: 40px;
    }
    }
    .good-btn {
      display: flex;
      justify-content: space-between;
      .price {
        font-size: 16px;
        color: red;
        line-height: 28px;
      }
      .van-icon-delete {
        font-size: 20px;
        margin-top:4px;
      }
    }    
  }
}
  .delete-buttion {
    width: 50%;
    height: 100%;
  }
}
  .empty {
    width: 50%;
    margin: 0 auto;
    text-align: center;
    margin-top: 200px;
  .empty-cart {
    width: 150px;
    margin-bottom: 20px;
  }
  .van-icon-smile-o {
    font-size: 50px;
  }
  .title {
    font-size: 16px;
    margin-bottom: 20px;
  }
}
.van-button--danger{
  height: 100%;
}

}
.van-submit-bar{
  bottom: 50px;
}
.cart-box .van-button--danger {
  height: 80%;
}
</style>